using System;
using System.Configuration;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;

using Microsoft.MSE.Catalog.Module.Configuration;
using Microsoft.Win32;

namespace Microsoft.MSE.Catalog.Module
{
    public static class Configurator
    {
        public static CatalogSvcConfig svcConfig;
        private static string svcConfigXml;

        public static void ReadConfig()
        {
            string regKey;
            regKey = SC.PlatformRegKey + @"\" + SC.ComponentName;

            svcConfig = ConfigurationManager.GetSection(SC.CatalogSvcConfigSettingName) as CatalogSvcConfig;

            if (svcConfig == null)
            {
                svcConfigXml = (string) Registry.GetValue(regKey, SC.CatalogSvcConfigSettingName, string.Empty);
                if (string.IsNullOrEmpty(svcConfigXml))
                    throw new ApplicationException(SC.CatalogSvcConfigSettingName +
                                                   " not found in app.config nor in Registry - " + SC.ComponentName +
                                                   " can not start");
                DataContractSerializer ser = new DataContractSerializer(typeof (CatalogSvcConfig));
                svcConfig = (CatalogSvcConfig) ser.ReadObject(XmlReader.Create(new StringReader(svcConfigXml)));
            }
        }
    }
}